package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Autowired
    private MapApi mapApi;

    /**
     * 设置默认地址
     *
     * @param flag
     * @param id
     */
    @Override
    @Transactional
    public void updateDefault(Integer flag, Long id) {
        //如果flag = 1 设置默认地址
        if (flag == 1){
            //取消之前的默认地址
            lambdaUpdate()
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .set(AddressBook::getIsDefault, 0)
                    .update();
        }
        //补全字段
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setIsDefault(flag);
        updateById(addressBook);
    }
    /**
     * 地址簿编辑
     *
     * @param id
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAddressById(Long id, AddressBookUpsertReqDTO dto) {
        //如果用户设置了默认地址  则查询数据库 取消之前的默认地址
        if (dto.getIsDefault() == 1){
            lambdaUpdate()
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .set(AddressBook::getIsDefault, 0)
                    .update();
        }
        //数据拷贝
        AddressBook addressBook = BeanUtil.copyProperties(dto, AddressBook.class);
        addressBook.setId(id);
        //处理经纬度
        handleLocation(dto,addressBook);
        //修改
        updateById(addressBook);
    }

    /**
     * 地址簿分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<AddressBookResDTO> getPage(AddressBookPageQueryReqDTO dto) {
        //设置分页参数
        Page<AddressBook> page = PageUtils.parsePageQuery(dto, AddressBook.class);
        //设置分页条件
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<AddressBook>()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDeleted, 0);
        //分页查询
        Page<AddressBook> list = baseMapper.selectPage(page, wrapper);

        //返回结果
        return PageUtils.toPage(list, AddressBookResDTO.class);
    }

    /**
     * 新增地址
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAddress(AddressBookUpsertReqDTO dto) {

        //获取用户id
        Long userId = UserContext.currentUserId();

        //如果新增用户设置了默认地址  则查询数据库 取消之前的默认地址
        if (dto.getIsDefault() == 1){
            lambdaUpdate()
                    .eq(AddressBook::getUserId, userId)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
        }

        //数据拷贝
        AddressBook addressBook = BeanUtil.copyProperties(dto, AddressBook.class);
        //设置用户id
        addressBook.setUserId(userId);


        handleLocation(dto, addressBook);

        //保存
        save(addressBook);
    }

    private void handleLocation(AddressBookUpsertReqDTO dto, AddressBook addressBook) {
        //如果用户没有设置经纬度  则根据地址解析经纬度

        if (ObjectUtil.isNull(dto.getLocation())){
            //解析地址 拼接地址
            String address = dto.getProvince() + dto.getCity() + dto.getCounty() + dto.getAddress();
            //远程调用高德接口 根据地址解析经纬度
            LocationResDTO locationDto = mapApi.getLocationByAddress(address);
            dto.setLocation(locationDto.getLocation());
        }

        //如果用户设置经纬度 则使用用户设置的经纬度
        if (ObjectUtil.isNotNull(dto.getLocation())){
            String location = dto.getLocation();
            //解析经度 并赋值
            addressBook.setLon(NumberUtil.parseDouble(location.split(",")[0]));
            //解析纬度 并赋值
            addressBook.setLat( NumberUtil.parseDouble(location.split(",")[1]));
        }
    }

    /**
     * 获取默认地址
     *
     * @return
     */
    @Override
    public AddressBookResDTO defaultAddress() {
        //获取当前登录用户
        Long userId = UserContext.currentUserId();
        //查询默认地址
        AddressBook add = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1)
                .one();
        if (ObjectUtil.isNull(add)){
            return null;
        }
        //转换为DTO
        return BeanUtil.copyProperties(add, AddressBookResDTO.class);
    }


    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }
}
